
<template>
  <div class="accountList">
    <div class="searchBox">
      <el-form :model="searchForm" ref="searchFormRef">
        <el-row>
          <el-form-item prop="title">
            <div class="item">
              <span v-html="'标题'" class="nameSpan"></span>
              <el-input
                size="mini"
                v-model="searchForm.title"
                placeholder="请输入标题"
              ></el-input>
            </div>
          </el-form-item>
          <el-form-item prop="status">
            <div class="item">
              <span v-html="'审核状态'" class="nameSpan"></span>
              <el-select filterable 
                clearable
                v-model="searchForm.status"
                placeholder="请选择审核状态"
                size="mini"
              >
                <el-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </div>
          </el-form-item>
          <el-form-item prop="enabled">
            <div class="item">
              <span v-html="'启用状态'" class="nameSpan"></span>
              <el-select filterable 
                clearable
                v-model="searchForm.enabled"
                placeholder="请选择状态"
                size="mini"
              >
                <el-option
                  v-for="item in enabledOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button
              @click="searchClick"
              icon="el-icon-search"
              type="primary"
              size="mini"
              >查询</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetClick"
              >重置</el-button
            >
          </el-form-item>
        </el-row>
      </el-form>
    </div>
    <div class="topBtn">
      <el-button
        size="mini"
        @click="addAccountClick"
        type="success"
        plain
        icon="el-icon-plus"
        v-has="'operation:news:add'"
        >新增资讯</el-button
      >
    </div>
    <div class="tableBox" ref="tableBoxRef">
      <el-table
        :height="605"
        v-loading="tableLoading"
        :header-cell-style="{
          background: '#F8F8F8',
          color: '#333',
          fontSize: '16px',
          fontWeight: '700',
        }"
        border
        :data="tableData"
        style="width: 100%"
      >
        <el-table-column prop="title" align="center" label="标题">
        </el-table-column>
        <el-table-column prop="createTime" align="center" label="创建时间">
          <template slot-scope="scope">{{
            scope.row.createTime | formatDate
          }}</template>
        </el-table-column>
        <el-table-column prop="createName" align="center" label="创建人">
        </el-table-column>
        <el-table-column prop="status" align="center" label="审核状态">
          <template slot-scope="scope">
            {{ statusFormatter[scope.row.status] }}
          </template>
        </el-table-column>
        <el-table-column prop="verifyTime" align="center" label="审核时间">
          <template slot-scope="scope">{{
            scope.row.verifyTime | formatDate
          }}</template>
        </el-table-column>
        <el-table-column prop="verifyName" align="center" label="审核人">
        </el-table-column>
        <el-table-column prop="enabled" align="center" label="启用状态">
          <template slot-scope="scope">
            <el-switch
              v-if="scope.row.status == 3"
              :disabled="permissions.indexOf('operation:news:enable') == -1"
              @change="statusChange(scope.row)"
              :active-value="1"
              :inactive-value="0"
              v-model="scope.row.enabled"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="view" align="center" label="浏览量">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.status != 3"
              icon="el-icon-edit-outline"
              size="mini"
              type="text"
              v-has="'operation:news:verify'"
              @click="auditClick(scope.row)"
              >审核</el-button
            >
            <el-button
              icon="el-icon-edit-outline"
              size="mini"
              type="text"
              v-has="'operation:news:info'"
              @click="getView(scope.row)"
              >预览</el-button
            >
            <el-button
              icon="el-icon-edit-outline"
              size="mini"
              type="text"
              v-has="'operation:news:edit'"
              @click="editClick(scope.row)"
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>

     <el-card class="footer" v-if="total > 0">
         <div>
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[15, 30, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
       </el-card>
    </div>

    <!-- 新增/修改权限 -->
    <el-dialog :close-on-click-modal="false" 
      :title="title"
      :visible.sync="addEditDialogVisible"
      width="1200px"
      @open="addEditDialogOpen"
      class="addEditAccountDialog"
    >
      <div class="content">
        <el-form
          :model="addEditForm"
          :rules="addEditRules"
          ref="addEditFormRef"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item prop="cover" label="封面图：">
                <div class="item">
                  <el-upload
                    :before-upload="beforeUploadImg"
                    accept=".jpg,.jpeg,.png,.JPG,.JPEG,.gif"
                    :on-progress="handleProgiress"
                    :action="$uploadUrl + '/2'"
                    list-type="picture-card"
                    :headers="postHead"
                    :show-file-list="false"
                    :on-success="handleProductPicSuccess"
                  >
                    <img
                      v-if="addEditForm.cover"
                      :src="addEditForm.cover"
                      style="width: 398px; height: 268px; display: block"
                    />
                    <i v-else class="el-icon-plus"></i>
                  </el-upload>
                  <el-progress
                    v-if="showJinDuTao"
                    style="
                      width: 200px;
                      margin-top: 10px;
                      position: absolute;
                      left: 0;
                      right: 0;
                      margin: auto;
                    "
                    :percentage="progressPercent"
                  />
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="title" label="标题：">
                <div class="item">
                  <el-input
                    size="mini"
                    v-model="addEditForm.title"
                    placeholder="请输入标题"
                  >
                  </el-input>
                </div>
              </el-form-item>
              <el-row>
                <el-col :span="12">
                  <el-form-item prop="sourceTitle" label="来源：">
                    <div class="item">
                      <el-input
                        size="mini"
                        v-model="addEditForm.sourceTitle"
                        placeholder="请输入来源"
                      >
                      </el-input>
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    prop="view"
                    label="浏览量："
                    style="margin-left: 20px"
                  >
                    <div class="item">
                      <el-input
                        size="mini"
                        v-model="addEditForm.view"
                        placeholder="请输入浏览量"
                      >
                      </el-input>
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item prop="sourceUrl" label="来源链接：">
                <div class="item">
                  <el-input
                    size="mini"
                    v-model="addEditForm.sourceUrl"
                    placeholder="请输入来源链接"
                  >
                  </el-input>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item prop="content" style="margin-top: 30px">
            <EditorBar
              style="width: 100%"
              v-model="addEditForm.content"
              :catchData="catchDataAgreement"
            ></EditorBar>
          </el-form-item>
          <el-form-item prop="attachments" label="附件上传：">
            <div class="item">
              <el-upload
                :before-upload="beforeUpload"
                :headers="postHead"
              :on-change='handleChange'
                class="upload-demo"
                :action="$uploadUrl + '/3'"
                :on-success="handleSuccess"
                :on-remove="handleRemove"
                :file-list="fileList"
              >
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
              <el-progress
                v-if="showJinDuTaoExcel"
                style="width: 200px; margin-top: 10px"
                :percentage="progressPercentExcel"
              />
              <div>上传文件大小不超过100M</div>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div class="btns">
        <el-button size="mini" @click="addEditDialogVisible = false"
          >取 消</el-button
        >
        <el-button
          v-clickForbidden
          size="mini"
          type="primary"
          @click="addEditDialogSaveClick"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import EditorBar from "@/components/WangEnduit.vue";
export default {
  data() {
    return {
      progressPercent: 0, // 进度条默认为0
      showJinDuTao: false, //控制进度条显示隐藏
      progressPercentExcel: 0, // 进度条默认为0
      showJinDuTaoExcel: false, //控制进度条显示隐藏
      postHead: { token: localStorage.token },
      title: "",
      searchForm: {
        title: "",
        status: "",
        enabled: "",
      },
      fileList: [],
      statusOptions: [
        { label: "待审核", value: 1 },
        { label: "审核不通过", value: 2 },
        { label: "审核通过", value: 3 },
      ],
      statusFormatter: {
        1: "待审核",
        2: "审核不通过",
        3: "审核通过",
      },
      enabledFormatter: {
        0: "禁用",
        1: "启用",
      },
      enabledOptions: [
        { label: "启用", value: 1 },
        { label: "禁用", value: 0 },
      ],
      tableLoading: false,
      tableHeight: 50,
      tableData: [],
      pageNum: 1,
      pageSize: 15,
      total: 0,
      addEditDialogVisible: false,
      addEditForm: {
        cover: "",
        title: "",
        sourceTitle: "",
        view: "",
        sourceUrl: "",
        content: "",
        attachments: [],
        description: "",
      },
      addEditRules: {
        cover: [{ required: true, message: "封面不能为空", trigger: "blur" }],
        title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
        sourceTitle: [
          { required: true, message: "来源不能为空", trigger: "blur" },
        ],
        view: [{ required: true, message: "浏览量不能为空", trigger: "blur" }],
      },
      roleOptions: [],
      editId: "",
    };
  },
  components: {
    EditorBar,
  },
  computed: {
    ...mapGetters(["permissions"]),
  },
  created() {
    this.getOperationList();
  },
  methods: {
        handleChange( file, fileList){
      
         if(file.status==='ready'){
          this.progressPercentExcel =0
          this.showJinDuTaoExcel=true
          const interval=setInterval(()=>{
            if(this.progressPercentExcel>=99){
              clearInterval(interval)
              return
            }
            this.progressPercentExcel+=1
          },100)
      }
      if(file.status==='success'){
        this.progressPercentExcel=100
         setTimeout(()=>{
          this.showJinDuTaoExcel=false
        },1000)
      }
       if(file.status==='fail'){
         setTimeout(()=>{
          this.progressPercentExcel = 0;
          this.showJinDuTaoExcel=false
        },1000)
      }
      
     
    },
    auditClick(row) {
      this.$router.push({
        path: "/operationManagement/industayView",
        query: { id: row.id, title: "审核" },
      });
    },
    getView(row) {
      this.$router.push({
        path: "/operationManagement/industayView",
        query: { id: row.id, title: "预览" },
      });
    },
    handleSuccess(file, fileList) {
      this.$nextTick(() => {
        this.fileList.push({
          url: file.result.filePath,
          name: fileList.name,
        });
      });
    },
    handleRemove(obj) {
      this.$nextTick(() => {
        this.fileList.forEach((item, index) => {
          if (item.url == obj.url) {
            this.fileList.splice(index, 1);
          }
        });
      });
    },
    beforeUploadImg(file) {
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
         this.$message.error("上传文件大小不能超过 10MB!");
            file=false
       return file
      }
      this.$message.warning("上传中,请稍等");
      this.showJinDuTao = true;
    
    },

    handleProgiress(event, file, fileList) {
      this.progressPercent = event.percent;
    },
    beforeUpload(file) {
    const isLt100M = file.size / 1024 / 1024 < 100;
    
      if (!isLt100M) {
         this.$message.error("上传文件大小不能超过 100MB!");
            file=false
       return file
      }
      
    },
    //基本信息富文本编辑
    catchDataAgreement(val) {
      this.addEditForm.content = val;
    },
    /**
     * 图片上传成功的事件
     * @param {*}
     */
    handleProductPicSuccess(res, file) {
      if (res.code == "00000") {
        this.addEditForm.cover = res.result.filePath;
      } else {
        this.$message.error(res.message);
      }
       setTimeout(()=>{
          this.showJinDuTao=false
        },1000)
    },
    /**
     * 新增资讯
     * @param {*}
     */
    addAccountClick() {
      this.title = "新增资讯";
      this.addEditDialogVisible = true;
      this.fileList = [];
    },
    searchClick() {
      this.pageNum = 1;
      this.getOperationList();
    },
    resetClick() {
      this.$refs.searchFormRef.resetFields();
      this.pageNum = 1;
      this.getOperationList();
    },

    /**
     * 获取用户列表
     * @param {*}
     */
    async getOperationList() {
      this.tableLoading = true;
      await this.$api
        .operationList({
          size: this.pageSize,
          page: this.pageNum,
          condition: {
            ...this.searchForm,
          },
        })
        .then((res) => {
          if (res.data.code == "00000") {
            this.total = res.data.result.total;
            this.tableData = res.data.result.records;
            this.tableLoading = false;
          }
        });
    },
    /**
     * 编辑按钮
     * @param {*} row
     */
    async editClick(row) {
      this.title = "编辑资讯";
      this.addEditDialogVisible = true;
      this.editId = row.id;
      await this.$api.operationDetail(this.editId).then((res) => {
        if (res.data.code == "00000") {
          this.$nextTick(() => {
            this.addEditForm = res.data.result;
            this.fileList = this.addEditForm.attachments;
          });
        }
      });
    },
    /**
     * 状态更新回调
     * @param {*} row
     */
    async statusChange(row) {
      try {
        const flag = row.enabled; // 点击之后的值
        row.enabled = row.enabled === 1 ? 0 : 1; // switch点击前的状态
        const confirmTips = flag === 1 ? "启用" : "停用";
        const confirmTextTips = flag === 1 ? "显示" : "隐藏";
        //确认框
        const confirm = await this.$confirm(
          `${confirmTips}后，资讯将在PC和小程序${confirmTextTips}，确定${confirmTips}吗？`,
          "提示",
          {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: "warning",
          }
        ).catch(() => false);
        if (!confirm) return false;
        row.enabled = row.enabled === 1 ? 0 : 1;
        if (row.enabled == 0) {
          const res = await this.$api.statusUsiForbidden(row.id);
          if (res.data.code == "00000") {
            this.$message.success("状态停用成功");
          }
        } else {
          const res = await this.$api.statusUsi(row.id);
          if (res.data.code == "00000") {
            this.$message.success("状态启用成功");
          }
        }

        this.getOperationList();
      } catch (error) {
        this.$message.error(error);
      }
    },

    /**
     * 切换页面大小
     * @param {*} val
     */
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.getOperationList();
    },

    /**
     * 页码切换
     * @param {*} val
     */
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageNum = val;
      this.getOperationList();
    },

    /**
     * 打开新增和修改的回调
     * @param {*}
     */
    addEditDialogOpen() {
      this.progressPercent = 0;
      this.showJinDuTao = false;
      this.progressPercentExcel = 0;
      this.showJinDuTaoExcel = false;
      if (this.$refs.addEditFormRef) this.$refs.addEditFormRef.resetFields();
    },
    ToText(A) {
      var input = A;
      return input
        .replace(/<(style|script|iframe)[^>]*?>[\s\S]+?<\/\1\s*>/gi, "")
        .replace(/<[^>]+?>/g, "")
        .replace(/\s+/g, " ")
        .replace(/ /g, " ")
        .replace(/&nbsp;/g, "");
    },
    /**
     * 编辑保存按钮
     * @param {*}
     */
    addEditDialogSaveClick() {
      this.addEditForm.description = this.ToText(
        this.addEditForm.content
      ).substring(0, 255);

      this.$refs.addEditFormRef.validate(async (boolean) => {
        if (boolean) {
          this.addEditForm.attachments = [];
          this.fileList.forEach((item) => {
            this.addEditForm.attachments.push(item.url);
          });

          let data = {
            id: this.editId,
            ...this.addEditForm,
          };
          if (this.title == "新增资讯") {
            data.id = "";
            await this.$api.addOperation(data).then((res) => {
              if (res.data.code == "00000") {
                this.$message.success("新增成功");
                this.getOperationList();
                this.addEditDialogVisible = false;
              }
            });
          } else {
            await this.$api.editOperation(data).then((res) => {
              if (res.data.code == "00000") {
                this.$message.success("修改成功");
                this.getOperationList();
                this.addEditDialogVisible = false;
              }
            });
          }
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.accountList {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 20px;
  .searchBox {
    .el-row {
      display: flex;
      flex-wrap: wrap;
      .el-form-item {
        margin-bottom: 0;
      }
      .item {
        display: flex;
        align-items: center;
        margin-right: 20px;
        position: relative;
        .nameSpan {
          padding-right: 10px;
          box-sizing: border-box;
          white-space: nowrap;
        }
        .el-input {
          width: 162px;
        }
      }
    }
  }
  .topBtn {
    margin: 10px 0;
    text-align: right;
  }
  .addEditAccountDialog {
    .el-form-item {
      .el-select {
        width: 100%;
      }
    }
    .btns {
      text-align: right;
      margin-bottom: 0;
    }
  }
}
/deep/.el-button--success.is-plain {
  color: #fff;
  border-color: #409eff;
  background-color: #409eff;
}
/deep/.el-form-item {
  margin-bottom: 12px;
}
.content {
  height: 60vh;
  overflow-x: hidden;
}
/deep/.el-upload--picture-card {
  width: 400px;
  height: 270px;
}
/deep/.el-upload--picture-card i {
  margin-top: 128px;
}
</style>